﻿using System;
using System.Data;
using System.Collections.Generic;
using System.IO;

using System.Windows.Forms;

namespace Gladkikh.Sims2.Combiner.Database
{
	public class Sims2Mdb : IDisposable
	{
		sims2addonsDataSet sims2Dataset;
		sims2addonsDataSetTableAdapters.Sims2AddonsTableAdapter adapter;

		public enum OpenBase { XML, MDB };
		OpenBase db;

		public event EventHandler OnDataBaseChanged;

		public OpenBase Db
		{
			get { return db; }
			set
			{
				db = value;
				if (OnDataBaseChanged != null)
					OnDataBaseChanged(this, new EventArgs());
			}
		}

		public void InitConnection()
		{
			sims2Dataset = new sims2addonsDataSet();
			adapter = new sims2addonsDataSetTableAdapters.Sims2AddonsTableAdapter();
			//adapter.Fill(sims2Dataset.Sims2Addons);

			//   if(File.Exists("Sims2.Addons.DB.xml"))
			// {
			//sims2Dataset.ReadXml("Sims2.Addons.DB.xml");
			//db = OpenBase.XML;
			//}
			//else
			if (File.Exists("sims2addons.mdb"))
			{
				adapter.Fill(sims2Dataset.Sims2Addons);
				db = OpenBase.MDB;
			}
			else
				RebuildDefaultDB();
		}

		private void RebuildDefaultDB()
		{
			MessageBox.Show("Так как не найдена ни одна из Баз Данных, то востановлена БД по умолчанию",
			                "Восстановлена БД",
			                MessageBoxButtons.OK);

			Uncompress();

			adapter.Fill(sims2Dataset.Sims2Addons);
			db = OpenBase.MDB;
		}

		private void Uncompress()
		{
			try
			{
				MemoryStream inStream = new MemoryStream(Gladkikh.Sims2.Combiner.Properties.Resources.sims2addons7zip, 0,
				                                         Gladkikh.Sims2.Combiner.Properties.Resources.sims2addons7zip.Length);
				
				FileStream outStream = new FileStream("sims2addons.mdb", FileMode.Create);
				
				byte[] properties = new byte[5];
				
				if (inStream.Read(properties, 0, 5) != 5)
					throw (new Exception("input .lzma is too short"));
				
				SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();
				decoder.SetDecoderProperties(properties);
				long outSize = 0;
				
				for (int i = 0; i < 8; i++)
				{
					int v = inStream.ReadByte();
					if (v < 0)
						throw (new Exception("Can't Read 1"));
					outSize |= ((long)(byte)v) << (8 * i);
				}
				
				long compressedSize = inStream.Length - inStream.Position;
				decoder.Code(inStream, outStream, compressedSize, outSize, null);
				
				inStream.Close();
				outStream.Close();
			}
			catch(IOException e)
			{
				
				MessageBox.Show(e.Message, "Some IO error happend when BD recreating");
				Application.Exit();
				
			}
		}

		public void Read(out List<Sims2Addon> inp)
		{
			inp = new List<Sims2Addon>(sims2Dataset.Sims2Addons.Rows.Count);

			foreach (DataRow row in sims2Dataset.Sims2Addons)
			{
				Sims2Addon add = new Sims2Addon();
				add.DisplayName = row["DisplayName"] as string;
				add.Exe = row["AddonExe"] as string;
				add.ExePath = row["AddonExePath"] as string;
				add.Name = row["Name"] as string;
				add.RegMask = row["RegData"] as string;
				add.Enabled = (bool)row["Enabled"];
				inp.Add(add);
			}
		}

		public void Write(List<Sims2Addon> add)
		{
			int i = 0;
			foreach (DataRow row in sims2Dataset.Sims2Addons)
			{
				row["DisplayName"] = add[i].DisplayName;
				row["AddonExe"] = add[i].Exe;
				row["AddonExePath"] = add[i].ExePath;
				row["Name"] = add[i].Name;
				row["RegData"] = add[i].RegMask;
				row["Enabled"] = add[i].Enabled;
				i++;
			}
			//if (db == OpenBase.MDB)
			adapter.Update(sims2Dataset.Sims2Addons);
			//    else
			//      sims2Dataset.WriteXml("Sims2.Addons.DB.xml");
		}

		public void Dispose()
		{
			throw new NotImplementedException();
		}
	}
}
